import Vue from 'vue'

//拦截器
const interceptors = {
	request: (param) => {
		param.url = myglobal.SITE_CONFIG.api + param.url
		return param;
	},
	response: (res) => {
		const data = res.data || null
		if (data && data.code == 401) {
			uni.removeStorageSync('token')
			uni.hideLoading()
			// uni.navigateTo({
			// 	url: '/pages/login/index'
			// })
		} else if (data && data.code == 403) {
			uni.hideLoading()
			// uni.navigateTo({
			// 	url: `/pages/address/index?logicId=${data.logicId}`
			// })
		}
	}
}

function request(param) {
	param = interceptors.request(param);
	const token = uni.getStorageSync('token')
	const requestPromise = new Promise((resolve, reject) => {
		uni.request({
			url: param.url,
			method: param.method,
			data: param.data,
			header: {
				'token': token
			},
			success: (res) => {
				interceptors.response(res);
				resolve(res);
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showModal({
					title: '提示',
					content: '网络断开...请稍后重试',
					showCancel: false,
					confirmColor: '#138FEA',
					success: function(res) {}
				})
				reject(err);
			}
		})
	})
	return requestPromise;
}

export default request
